#include "pt100.h"

#define PT100_THERMOTABLE_SIZE              106
#define PT100_THERMOTABLE_START_TEMPERATURE -200

const float Pt100_typeThermoTable[PT100_THERMOTABLE_SIZE] = {
    18.52,  22.83,  27.10,  31.34,  35.54,  39.72,  43.88,  48.00,  52.11,  56.19,  60.26,  64.30,  68.33,  72.33,  76.33,  80.31,  84.27,  88.22,  92.16,  96.09,  100.00, 103.90,
    107.79, 111.67, 115.54, 119.40, 123.24, 127.08, 130.90, 134.71, 138.51, 142.29, 146.07, 149.83, 153.58, 157.33, 161.05, 164.77, 168.48, 172.17, 175.86, 179.53, 183.19, 186.84,
    190.47, 194.10, 197.71, 201.31, 204.90, 208.48, 212.05, 215.61, 219.15, 222.68, 226.21, 229.72, 233.21, 236.70, 240.18, 243.64, 247.09, 250.53, 253.96, 257.38, 260.78, 264.18,
    267.56, 270.93, 274.29, 277.64, 280.98, 284.30, 287.62, 290.92, 294.21, 297.49, 300.75, 304.01, 307.25, 310.49, 313.71, 316.92, 320.12, 323.30, 326.48, 329.64, 332.79, 335.93,
    339.06, 342.18, 345.28, 348.38, 351.46, 354.53, 357.59, 360.64, 363.67, 366.70, 369.71, 372.71, 375.70, 378.68, 381.65, 384.60, 387.55, 390.48

};

int half_search(const float A[], int n, double key)
{
    int    low, high, mid;
    double keytemp;
    keytemp = key;
    low     = 0;
    high    = n - 1;

    if (keytemp > A[high])
    {
        return high;
    }
    else if (keytemp < A[0])
    {
        return 0;
    }

    while (low <= n - 1 && high >= 0)
    {
        mid = (low + high + 1) / 2;
        if (A[mid] <= keytemp && keytemp <= A[mid + 1])
        {
            return mid;
        }
        if (A[mid] < keytemp)
        {
            low = mid + 1;
        }
        if (A[mid] > keytemp)
        {
            high = mid - 1;
        }
    }
    return -1;
}

float get_pt100_temp(float oumu_estimation)
{
    int   indexFind   = 0;
    int   A1          = 0;
    int   A2          = 0;
    float temperature = 0;
    indexFind         = half_search(Pt100_typeThermoTable, 106, oumu_estimation);
    // 没找到
    if (indexFind == -1)
    {
        indexFind   = 0;
        A1          = 0;
        A2          = 0;
        temperature = A1;
        temperature += PT100_THERMOTABLE_START_TEMPERATURE;
    }
    // 索引到最大值情况
    else if (indexFind == PT100_THERMOTABLE_SIZE - 1)
    {
        A1          = indexFind * 10;
        A2          = indexFind * 10;
        temperature = A1;
        temperature += PT100_THERMOTABLE_START_TEMPERATURE;
    }
    // 正常情况
    else
    {
        A1          = Pt100_typeThermoTable[indexFind];
        A2          = Pt100_typeThermoTable[indexFind + 1];
        temperature = (double)((oumu_estimation - A1) / (A2 - A1) * 10 + indexFind * 10);
        temperature += PT100_THERMOTABLE_START_TEMPERATURE;
    }
}